
import mysql.connector
class MyDB(object):
    def __init__(self):
        self.conn = mysql.connector.connect(user='root', password='123456', database='test')


    '''
    参数2以后会改成传入一组sql语句:
    ('sql1','sql2','sql3')
    '''
    def doSql(self, sql, params = None):
        self.cursor = self.conn.cursor()
        self.cursor.execute(sql, params)
        if sql.startswith('insert') or sql.startswith('update') or sql.startswith('delete'):
            res = self.cursor.rowcount
            self.conn.commit()
            self.cursor.close()
            return res
        elif sql.startswith('select'):
            res = self.cursor.fetchall()
            self.cursor.close()
            return res
        elif sql.startswith('create table') or sql.startswith('drop table'):
            return 1

    def close(self):
        self.conn.close()


#######################################################################
db = MyDB()

#创建表：
db.doSql('create table if not exists p_user (id varchar(20) primary key, name varchar(20)) engine=innodb default charset=utf8 auto_increment=1;')

#插入
affectRowCount = db.doSql('insert into p_user (id, name) values (%s, %s)', ('2', 'Michael 王'))
if affectRowCount == 1:
    print('插入成功')
else:
    print('插入失败')

#查询
results = db.doSql('select * from p_user')
print(results)

db.close()













#
